# !/bin/bash

oplib_dir="$project_dir/third-party/tx8be-oplib"
oplib_url="git@gitlab.tsingmicro.com:tx8_toolchain/tx8be-oplib.git"
# oplib_url="http://192.168.100.107/tx8_toolchain/tx8be-oplib"

oplib_cmake="$oplib_dir/CMakeLists.txt"
oplib_commit_id_435=""

oplib_release_dir="$oplib_dir/release"
oplib_include_dir="$oplib_release_dir/riscv/tx8-yoc-rt-thread-smp/include"
oplib_lib="$oplib_release_dir/riscv/tx8-yoc-rt-thread-smp/lib/libkcorert.a"

echo -e "Using oplib DIR_PATH: \033[32m $oplib_dir \033[0m"

function build_target_oplib() {
    local repo_dir="$1"
    local release_dir="$2"

    if [ -d "$release_dir" ]; then
        # echo -e "Release : \033[47;34m $release_dir \033[0m exists."
        echo -e "Release : \033[34m $release_dir \033[0m exists."
        # return 0
    fi

    if [ -f "$oplib_lib" ]; then
        # echo -e "Library : \033[47;34m $oplib_lib \033[0m exists, Using this lib."
        echo -e "Library : \033[34m $oplib_lib \033[0m exists, Using this lib."
        return 0
    fi

    if [ -d "$repo_dir" ]; then
        echo -e "Building  : \033[34m $repo_dir \033[0m"
        pushd $repo_dir >/dev/null 2>&1
        make soc_tx81 >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            echo -e "\033[32mSucceed building $repo_dir.\033[0m"
            # return 0
        fi
        popd >/dev/null 2>&1
        return 0
    else
        echo -e "\033[47;32mFailed to build $repo_dir.\033[0m"
        return 1
    fi
}

function main_oplib() {
    # check_git_install
    check_repo_exists $oplib_dir $oplib_url

    if [ $? -eq 0 ]; then
        if [ ! -z "$oplib_commit_id_435" ]; then
            echo -e "Succeed cloning $oplib_url."
            git checkout "$oplib_commit_id_435"
            echo -e "Checkout: $oplib_commit_id_435 ."
        else
            COMMIT_ID=$(git rev-parse --short HEAD)
            echo -e "Checkout: "$COMMIT_ID" . "
        fi
    fi
    
    build_target_oplib $oplib_dir $oplib_release_dir
}

main_oplib
